//
//  VerticalScrollView.swift
//  SmallParts
//
//  Created by 航汇聚 on 2019/10/9.
//  Copyright © 2019 BellaZhou. All rights reserved.
//

import UIKit

class VerticalScrollView: UIView {
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var scrollContentView: UIStackView!
    var timer: Timer?
    let duration = 1.5
    var indexOfPage = 0
    open class func loadVerticalScrollView() -> VerticalScrollView {
        let loopView = Bundle.main.loadNibNamed("VerticalScrollView", owner: self, options: nil)?.first as! VerticalScrollView
        return loopView
    }
    func autoScrollByDuration(_ duration: TimeInterval) {
        let offsetWidth = self.bounds.size.width
        let offsetHeight = self.bounds.size.height
        let countOfScrollContentSubViews = self.scrollContentView.subviews.count
        
        timer = Timer.scheduledTimer(withTimeInterval: duration, repeats: true) { (timer) in
            var offsetPoint = CGPoint(x: 0, y: CGFloat(Float(offsetHeight)*Float(self.indexOfPage)))
            if self.indexOfPage > countOfScrollContentSubViews-1 {
                self.indexOfPage = 0
                self.scrollView.contentOffset = CGPoint(x: 0, y: -offsetHeight)
                offsetPoint = CGPoint(x: 0, y: 0)
            }
            self.scrollView.scrollRectToVisible(CGRect(x: offsetPoint.x, y: offsetPoint.y, width: offsetWidth, height: offsetHeight), animated: true)
            self.indexOfPage += 1
        }
        timer!.fire()
    }
}
extension VerticalScrollView: UIScrollViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        timer?.invalidate()
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.indexOfPage = Int(scrollView.contentOffset.y/scrollView.bounds.size.height)
        self.autoScrollByDuration(duration)
    }
}
